package cn.mengfly.testnrz.crazyIm.nettyserver;

import cn.mengfly.testnrz.nio.NioDemoConfig;
import lombok.Data;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * IM节点的POJO类,用来标识Netty服务器
 *
 * @author Mengfly
 */
@Data
public class ImNode implements Comparable<ImNode> {

    /**
     * Worker 的Id， Zookeeper负责生成
     */
    private long id;

    /**
     * Netty 服务的连接数
     */
    private AtomicInteger balance;

    /**
     * Netty 服务IP
     */
    private String host;

    /**
     * Netty 服务端口
     */
    private String port;


    public ImNode(String host, String port) {
        this.host = host;
        this.port = port;
    }

    public static ImNode getLocalInstance() {
        try {
            return new ImNode(InetAddress.getLocalHost().getHostAddress(), String.valueOf(NioDemoConfig.SOCKET_PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final ImNode node = (ImNode) o;
        return id == node.id && Objects.equals(host, node.host) && Objects.equals(port, node.port);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, host, port);
    }

    /**
     * 用来负载升序排列
     *
     * @param node node
     * @return compare
     */
    @Override
    public int compareTo(ImNode node) {
        int weight1 = this.getBalance().get();
        int weight2 = this.getBalance().get();
        if (weight1 > weight2) {
            return 1;
        } else if (weight1 < weight2) {
            return -1;
        }
        return 0;
    }
}
